Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
How to transfer "this" in class

I have a class like that

class Message {
  initTextForm() {
    document.addEventListener('input', function(e) {
      this.addTextMessage(e.target.innerHTML);
    });
  }
  addTextMessage(text) {
    console.log(text);
  }
}

new Message().initTextForm()
<input/>

How to transfer class "this" into event listener?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Use an arrow function:

class Message {
  initTextForm() {
    document.addEventListener('input', (e) => {
      this.addTextMessage(e.target.value);
    });
  }
  addTextMessage(text) {
    console.log(text);
  }
}

new Message().initTextForm()
<input/>

about 4 years ago · Juan Pablo Isaza Report

0

You can use two ways:

  1. arrow function

class Message {
  initTextForm() {
    document.addEventListener('input', (e) => {
      this.addTextMessage(e.target.value);
    });
  }
  addTextMessage(text) {
    console.log(text);
  }
}

new Message().initTextForm()
<input/>

  1. binding function

class Message {
  constructor(){
      this.addTextMessage = this.addTextMessage.bind(this);
  }
  initTextForm() {
    document.addEventListener('input', this.addTextMessage)
  }
  addTextMessage(e) {
    console.log(e.target.value);
  }
}

new Message().initTextForm()
<input/>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!